package net.schastny.shopmanager.dao;

import java.util.List;

import javax.management.Query;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import net.schastny.shopmanager.domain.BaseOrder;
import net.schastny.shopmanager.domain.Order;
@Repository
public class BaseOrderDAOImpl implements BaseOrderDAO {
	
	/*Аннотация позволяет автоматически установить значение поля SessionFactory.
	 */
	@Autowired
	private SessionFactory sessionFactory;
	
	public void addBaseOrder(BaseOrder baseOrder) {
		// TODO Auto-generated method stub
		sessionFactory.getCurrentSession().save(baseOrder);
	}

	@SuppressWarnings("unchecked")	
	public List<BaseOrder> listBaseOrder() {
		// TODO Auto-generated method stub
		System.out.println("-------- List Count" + sessionFactory.getCurrentSession().createQuery("from BaseOrder").list().size()) ;
		return sessionFactory.getCurrentSession().createQuery("from BaseOrder")
	            .list();
	}

	public void removeBaseOrder(Integer id) {
		// TODO Auto-generated method stub
		BaseOrder baseOrder = (BaseOrder) sessionFactory.getCurrentSession().load(
				BaseOrder.class, id);
        if (null != baseOrder) {
            sessionFactory.getCurrentSession().delete(baseOrder);
        }
	}

	public BaseOrder getBaseOrder(Integer id) {
		// TODO Auto-generated method stubs
	//	System.out.println ("Result get = " + sessionFactory.getCurrentSession().createQuery("FROM BaseOrder as p WHERE p.id="+id).uniqueResult());
		return (BaseOrder) sessionFactory.getCurrentSession().createQuery("FROM BaseOrder as p WHERE p.baseorderId="+id).uniqueResult();

	}

	public void editBaseOrder(BaseOrder baseOrder) {
		// TODO Auto-generated method stub
		
		// Retrieve session from Hibernate
		Session session = sessionFactory.getCurrentSession();
		
		// Retrieve existing person via id
		BaseOrder existingBaseOrder = (BaseOrder) session.get(BaseOrder.class, baseOrder.getBaseorderId());
		System.out.print("existingBaseOrder = "+existingBaseOrder.toString());
		// Assign updated values to this person
		existingBaseOrder.setBaseorderId(baseOrder.getBaseorderId());
		existingBaseOrder.setStatusBaseOrder(baseOrder.getStatusBaseOrder());
		existingBaseOrder.setInvoice(baseOrder.getInvoice());
		existingBaseOrder.setComission(baseOrder.getComission());
		existingBaseOrder.setShip(baseOrder.getShip());
		existingBaseOrder.setDelivery(baseOrder.getDelivery());

		// Save updates
		session.save(existingBaseOrder);
		
	}

	public List<Order> getOrders() {
		// TODO Auto-generated method stub
		return null;
	}
	


}
